package com.youxin.busfoundation.common;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.youxin.busfoundation.bean.BusinessMessages;
import com.youxin.busfoundation.bean.ResponseMessage;
import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.foundation.lang.BaseException;
import com.youxin.foundation.utils.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 全局异常类
 * 
 * @author yingde.cao
 *
 */

public class BaseExceptionHandler extends AbstractErrorController {
	private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(BaseExceptionHandler.class);

	public BaseExceptionHandler(ErrorAttributes errorAttributes) {
		super(errorAttributes);
	}

	@Override
	public String getErrorPath() {
		return "/error";
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseObject error(HttpServletRequest request) {
		HttpStatus status = getStatus(request);		
		final Object exceptionObj = (Object) request.getAttribute("javax.servlet.error.exception");
		if (exceptionObj != null) {
			if (exceptionObj instanceof Throwable) {
				Throwable throwable = (Throwable) exceptionObj;
				Throwable innerException = throwable.getCause();
				if (innerException != null) {
					if (innerException instanceof BaseException)
					{						
						return ResponseObject.systemError(innerException);
					}
					if (innerException instanceof NullPointerException
							|| innerException instanceof IllegalArgumentException
							|| innerException instanceof IllegalStateException) {
						logger.error("参数异常错误", innerException);
						return ResponseObject.userFailure(StringUtils.isNullOrEmptySet(innerException.getMessage(),"参数异常"));
					}
					logger.error("application error", throwable);
					return ResponseObject.systemError(throwable);
				}
			}
			logger.error("application error:" + exceptionObj.toString());
			return ResponseObject.systemError(exceptionObj.toString());
		}

		return new ResponseObject(status.value(), status.getReasonPhrase());
	}
}
